<?php
defined('YANGJIFANG') or die('没有权限！');

class Db{

    protected $conn = null;

    public function __construct(){
        $this->conn = mysqli_connect('123.184.18.163','root','albert','yangjifang');
    }


    public function getList($sql){
        $result = mysqli_query($this->conn,$sql);
        $rows = [];
        while($row = mysqli_fetch_assoc($result)){
            array_push($rows,$row);
        }
        return $rows;
    }

    public function getOne($sql){
        $result = mysqli_query($this->conn,$sql);
        $result = mysqli_fetch_assoc($result);
        return $result;
    }


    public function insert($data,$table){
        if(!is_array($data) || empty($data)){
            return false;
        }
        $columns = '';
        $values = '';
        foreach( $data as $key => $val ){
            $columns .= $key.',';
            $val = is_string($val)?"'{$val}'":$val;
            $values .= $val.',';
        }
        $columns = trim($columns,',');
        $values = trim($values,',');
        $sql ="insert into {$table} ({$columns}) values ($values) ";

        mysqli_query($this->conn,$sql);
        $error = mysqli_error($this->conn);
        if($error){
            throw new Exception($error);
        }
        return mysqli_insert_id($this->conn);
    }

    public function delete($id,$table){
        $sql = "delete from {$table} where id = {$id}";
        mysqli_query($this->conn,$sql);
        return mysqli_affected_rows($this->conn);
    }

    public function update($data,$id,$table){
        if(!is_array($data) || empty($data)){
            return false;
        }

        $set = '';
        foreach( $data as $key => $val ){
            $val = is_string($val)?"'{$val}'":$val;
            $set .= " {$key} = {$val} ,";
        }

        $set = trim($set,',');
        $sql =" update {$table} set {$set} where id = {$id}";
        
        mysqli_query($this->conn,$sql);
        $error = mysqli_error($this->conn);
        if($error){
            throw new Exception($error);
        }
        return mysqli_insert_id($this->conn);
    }
}